package cn.chiship.bs.api.biz.service;

import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author LiJian
 */
@Component
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(RedisService.class);

    /**
     * 设置有效时间
     *
     * @param key  健值
     * @param time 时间（单位：s）
     * @return 标识
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0L) {
                this.redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }

            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 获得有效时间
     *
     * @param key 健值
     * @return 标识
     */
    public long getExpire(String key) {
        return this.redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 是否包含指定的key
     *
     * @param key 键值
     * @return 标识
     */
    public boolean hasKey(String key) {
        try {
            return this.redisTemplate.hasKey(key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 删除集合对象
     *
     * @param collection 集合
     */
    public boolean del(final Collection<String> collection) {
        if (!StringUtil.isNull(collection)) {
            return this.redisTemplate.delete(collection) > 0;
        }
        return false;

    }

    /**
     * 删除单个对象
     *
     * @param key 键值
     * @return 标识
     */
    public boolean del(final String key) {
        if (!StringUtil.isNullOrEmpty(key)) {
            return this.redisTemplate.delete(key);
        }
        return false;

    }

    /**
     * 缓存基本对象，Interger,String,实体等
     *
     * @param key   键值
     * @param value 缓存值
     * @return 标识
     */
    public boolean set(String key, Object value) {
        try {
            this.redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 缓存基本对象，Interger,String,实体等
     *
     * @param key   键值
     * @param value 缓存值
     * @param time  时间（单位：s）
     * @return 标识
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0L) {
                this.redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                this.set(key, value);
            }
            return true;
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return false;
        }
    }

    /**
     * 获得缓存的基本对象
     *
     * @param key 缓存的健值
     * @return 标识
     */
    public Object get(String key) {
        return key == null ? null : this.redisTemplate.opsForValue().get(key);
    }

    /**
     * 获得缓存的Map 指定Key的值
     *
     * @param key  缓存的健值
     * @param item hash Key
     * @return 标识
     */
    public Object hget(final String key, final String item) {
        return this.redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获得缓存的Map
     *
     * @param key 缓存的健值
     * @return 标识
     */
    public Map<Object, Object> hget(final String key) {
        return this.redisTemplate.opsForHash().entries(key);
    }

    /**
     * 删除Hash中的值
     *
     * @param key  缓存的健值
     * @param hKey hash Key
     * @return 标识
     */
    public boolean hdel(String key, Object... hKey) {
        return this.redisTemplate.opsForHash().delete(key, hKey) > 0;
    }

    /**
     * 向Hash中存入数据
     *
     * @param key   缓存的健值
     * @param item  条目
     * @param value 值
     * @return 标识
     */
    public boolean hset(String key, String item, Object value) {
        try {
            this.redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 向Hash中存入数据
     *
     * @param key   缓存的健值
     * @param item  条目
     * @param value 值
     * @param time  时间
     * @return 标识
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            this.redisTemplate.opsForHash().put(key, item, value);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 判断Hash是否包含指定Key
     *
     * @param key  键值
     * @param item 条目
     * @return 标识
     */
    public boolean hHasKey(String key, String item) {
        return this.redisTemplate.opsForHash().hasKey(key, item);
    }


    public long incr(String key, long delta) {
        if (delta < 0L) {
            throw new BusinessException("递增因子必须大于0");
        } else {
            return this.redisTemplate.opsForValue().increment(key, delta);
        }
    }

    public long decr(String key, long delta) {
        if (delta < 0L) {
            throw new BusinessException("递减因子必须大于0");
        } else {
            return this.redisTemplate.opsForValue().increment(key, -delta);
        }
    }


    public boolean hmset(String key, Map<String, Object> map) {
        try {
            this.redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception var4) {
            logger.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            this.redisTemplate.opsForHash().putAll(key, map);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return false;
        }
    }


    public double hincr(String key, String item, double by) {
        return this.redisTemplate.opsForHash().increment(key, item, by);
    }

    public double hdecr(String key, String item, double by) {
        return this.redisTemplate.opsForHash().increment(key, item, -by);
    }

    public Set<Object> sGet(String key) {
        try {
            return this.redisTemplate.opsForSet().members(key);
        } catch (Exception var3) {
            logger.error(var3.getMessage(), var3);
            return Collections.emptySet();
        }
    }

    public boolean sHasKey(String key, Object value) {
        try {
            return this.redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception var4) {
            logger.error(var4.getMessage(), var4);
            return false;
        }
    }

    public long sSet(String key, Object... values) {
        try {
            return this.redisTemplate.opsForSet().add(key, values);
        } catch (Exception var4) {
            logger.error(var4.getMessage(), var4);
            return 0L;
        }
    }

    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = this.redisTemplate.opsForSet().add(key, values);
            if (time > 0L) {
                this.expire(key, time);
            }

            return count;
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return 0L;
        }
    }

    public long sGetSetSize(String key) {
        try {
            return this.redisTemplate.opsForSet().size(key);
        } catch (Exception var3) {
            logger.error(var3.getMessage(), var3);
            return 0L;
        }
    }

    public long setRemove(String key, Object... values) {
        try {
            return this.redisTemplate.opsForSet().remove(key, values);
        } catch (Exception var4) {
            logger.error(var4.getMessage(), var4);
            return 0L;
        }
    }

    public List<Object> lGet(String key, long start, long end) {
        try {
            return this.redisTemplate.opsForList().range(key, start, end);
        } catch (Exception var7) {
            logger.error(var7.getMessage(), var7);
            return Collections.emptyList();
        }
    }

    public long lGetListSize(String key) {
        try {
            return this.redisTemplate.opsForList().size(key);
        } catch (Exception var3) {
            logger.error(var3.getMessage(), var3);
            return 0L;
        }
    }

    public Object lGetIndex(String key, long index) {
        try {
            return this.redisTemplate.opsForList().index(key, index);
        } catch (Exception var5) {
            logger.error(var5.getMessage(), var5);
            return null;
        }
    }

    public boolean lSet(String key, Object value) {
        try {
            this.redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception var4) {
            logger.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean lSet(String key, Object value, long time) {
        try {
            this.redisTemplate.opsForList().rightPush(key, value);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return false;
        }
    }

    public boolean lSet(String key, List<Object> value) {
        try {
            this.redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception var4) {
            logger.error(var4.getMessage(), var4);
            return false;
        }
    }

    public boolean lSet(String key, List<Object> value, long time) {
        try {
            this.redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return false;
        }
    }

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            this.redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return false;
        }
    }

    public long lRemove(String key, long count, Object value) {
        try {
            return this.redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception var6) {
            logger.error(var6.getMessage(), var6);
            return 0L;
        }
    }

    /**
     * 获得缓存基本对象的列表
     */
    public Set<String> keys(final String keyPrefix) {
        String realKey = keyPrefix + "*";

        /*try {
            return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
                Set<String> binaryKeys = new HashSet<>();
                Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(realKey).count(Integer.MAX_VALUE).build());
                while (cursor.hasNext()) {
                    binaryKeys.add(new String(cursor.next()));
                }

                return binaryKeys;
            });
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }*/

        return Collections.emptySet();
    }

    public void removeAll(String keyPrefix) {
        try {
            Set<String> keys = keys(keyPrefix);
            del(keys);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }

}
